//路由鉴权
import nprogress from "./utils/nprogress"
import router from "@/router"
import piniaStore from "./stores/index"
import {useUserStore} from "@/stores/modules/user"
import {GET_REFRESH_TOKEN, GETTOKEN, GETUSERINFO} from "./utils/local"
import {message} from "@/Hooks/Element-plus"
import {$t} from '@/utils/i18n'

//在其他文件拿pinia数据，需要传入pinia实例
const userStore = useUserStore(piniaStore)

//白名单页面
const whiteList = ["login", "home", "about", "introduction"]

const refreshToken = async () => {
    try {
        const flag = await userStore.getUserInfo()
        if (flag) {
            return true
        } else {
            message("error", $t('messageBox.loginError'))
            userStore.loginOut()
            return false;
        }
    } catch (e) {
        message("error", $t('messageBox.loginError'))
        return false;
    }
}

//全局前置守卫
router.beforeEach(async (to, from, next) => {
    nprogress.start()
    const title = to.meta?.title;
    if (title) {
        document.title = `${$t(String(title))} - ${$t('common.appName')}`
    } else {
        document.title = $t('common.appName')
    }
    //用户信息
    const userInfo = userStore.userinfo || GETUSERINFO()
    console.log("userInfo", userInfo)
    if (to.meta?.auth === false || to.meta?.isHome === true) {
        next();
        return;
    }
    if (GETTOKEN()) {
        if (to.name && whiteList.indexOf(String(to.name)) === -1) {
            //判断有没有用户信息
            if (Object.keys(userInfo).length === 0) {
                const flag: boolean = await refreshToken();
                if (flag) {
                    next({...to})
                } else {
                    next({path: "/login", query: {url: to.path}})
                }
            } else {
                next()
            }
        } else {
            next({path: "/"})
        }
    } else {
        if (to.name && whiteList.indexOf(String(to.name)) === -1) {
            const flag: boolean = await refreshToken();
            if (flag) {
                next({...to})
            } else {
                next({path: "/login", query: {url: to.path}})
            }
        } else {
            next()
        }
    }
})

//全局后置守卫
router.afterEach((to, from, next) => {
    nprogress.done()
})
